package com.sso.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author : alex
 * @date : 2020/1/28
 */
public class TokenUtil {
    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);
    /**
     * Token的过期时间
     */
    private static final Integer EXPIRE_TIME = 24 * 60 * 60;
    /**
     * Token的私钥
     */
    private static final String TOKEN_SECRET = "token_secret";

    public static String createToken(String userName) {
        try {
            // 设置过期时间
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.SECOND, EXPIRE_TIME);
            Date expireDate = nowTime.getTime();
            //私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userName", userName)
                    .withIssuedAt(new Date())
                    .withExpiresAt(expireDate)
                    .sign(algorithm);
        } catch (Exception e) {
            logger.error("CreateToken Error", e);
            return null;
        }
    }

    /**
     * 检验token是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            //未验证通过会抛出异常
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            logger.error("verify Error", e.getMessage());
            return false;
        }
    }

    /**
     * 获取自定字段
     */
    public static Map<String, Claim> getClaims(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            return decodedJWT.getClaims();
        } catch (Exception e) {
            logger.error("getClaims Error", e);
            return Collections.EMPTY_MAP;
        }
    }

    /**
     * 获取JWT
     */
    public static DecodedJWT getDecoded(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        } catch (UnsupportedEncodingException e) {
            logger.error("getDecoded Error", e);
            return null;
        }
    }

    public static void main(String[] args) {
        String token = TokenUtil.createToken("zhansan");
        System.out.println(TokenUtil.verify(token));
        Map<String, Claim> claims = TokenUtil.getClaims(token);
        Claim userName = claims.get("userName");
        System.out.println(userName.asString());
        DecodedJWT jwt = TokenUtil.getDecoded(token);
        System.out.println(jwt.getType());
        System.out.println(jwt.getPayload());
        System.out.println(jwt.getSignature());
        System.out.println(jwt.getToken());
    }
}